﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.ValueProviders;
using System.Net.Http;
using System.Globalization;
using System.Web.Http;
using System.Collections.Specialized;
using System.Runtime.Remoting.Messaging;
namespace Xinchen.SOA.Server.ServiceHosting
{
    public class ValueProvider : IValueProvider
    {
        private IEnumerable<KeyValuePair<string, string>> _queryParameters;
        private HttpContent _httpContent;
        private HttpActionContext _context;

        public ValueProvider(HttpActionContext context)
        {
            _context = context;
            _httpContent = context.Request.Content;
            _queryParameters = context.Request.GetQueryNameValuePairs();
        }
        public bool ContainsPrefix(string prefix)
        {
            return _queryParameters.Any(x => x.Key == prefix);
        }

        NameValueCollection _formDatas = (NameValueCollection)CallContext.LogicalGetData("$formDatas");

        public ValueProviderResult GetValue(string key)
        {
            var value = _queryParameters.FirstOrDefault(x => x.Key == key).Value;
            if (string.IsNullOrWhiteSpace(value))
            {
                if (_formDatas == null)
                {
                    if (_httpContent.IsFormData())
                    {
                        if (_formDatas == null)
                        {
                            _formDatas = _httpContent.ReadAsFormDataAsync().Result;
                            CallContext.LogicalSetData("$formDatas", _formDatas);
                        }
                    }
                    else
                    {
                        throw new HttpResponseException(_context.Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, string.Format("未在URL中找到名为{0}的参数，此时必须传入表单参数或json或xml参数", key)));
                    }
                }
                value = _formDatas[key];
                if (string.IsNullOrWhiteSpace(value))
                {
                    throw new HttpResponseException(_context.Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, string.Format("未在URL中找到名为{0}的参数，也未在表单中找到该参数", key)));
                }
            }
            return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
        }
    }
}
